package nil.ed.simulator.request.biz.qq.activity;

import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import nil.ed.simulator.request.client.JsFunc;
import nil.ed.simulator.request.client.activity.AbstractHttpActivity;
import nil.ed.simulator.request.client.activity.BuiltInAttrs;
import nil.ed.simulator.request.enums.ActivityGroup;
import nil.ed.simulator.request.enums.events.EventMode;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.bus.EventBus;
import nil.ed.template.FreeMarkerTemplateEngineAdapter;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.openjdk.nashorn.api.scripting.AbstractJSObject;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * App Index 活动.
 * @author lidelin.
 */
@Slf4j
public class Seq004CheckActivity extends AbstractHttpActivity {

    private static final String CHECK_URL = "https://ssl.ptlogin2.qq.com/check?regmaster=&pt_tea=2&pt_vcode=1&uin=${qq}&appid=2001601&js_ver=22030810&js_type=1&login_sig=${cookie_pt_login_sig}&u1=${appIndexSiteUrlEncoded}&r=${rand}&pt_uistyle=40&daid=&pt_3rd_aid=0";

    private final EventBus eventBus;

    @Inject
    public Seq004CheckActivity(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    @Override
    protected HttpUriRequest getRequest(Map<String, Object> attrMap) {
        attrMap.put("rand", String.valueOf(Math.random()));
        String url = FreeMarkerTemplateEngineAdapter.INSTANCE.process(CHECK_URL, attrMap);
        log.info("qq = {}, check url = {}", attrMap.get("qq"), url);
        return new HttpGet(url);
    }

    @Override
    protected boolean doFinalProcess(HttpResponse response, Map<String, Object> customAttrMap) {
        try {
            String content = String.join("\n", IOUtils.readLines(response.getEntity().getContent(), StandardCharsets.UTF_8));
            AbstractJSObject jo = (AbstractJSObject) JsFunc.JS_ENGINE.eval("callback_" + content);
            jo.keySet().forEach(prop -> customAttrMap.put(prop, String.valueOf(jo.getMember(prop))));
            log.info("qq = {}, check content = {}", customAttrMap.get("qq"), content);
            if (!"0".equals(String.valueOf(jo.getMember("checkVC_ret")))) {
                eventBus.publish(Event.builder()
                        .eventMode(EventMode.ASYNC)
                        .data(customAttrMap.get(BuiltInAttrs.ENTITY_ATTR))
                        .eventType(EventType.NEED_VC)
                        .source(null)
                        .build());
                customAttrMap.put("need.vc", true);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
        return true;
    }

    @Override
    public ActivityGroup getGroup() {
        return ActivityGroup.QQ_LOGIN;
    }

    @Override
    public int getSort() {
        return 20;
    }
}
